package app.framework.security;

import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.*;

/**
 * 本地化的用户认证信息：
 * 应用程序结合项目实际情况进行适配改造即可
 */
public class LocalUserDetails implements UserDetails {
    private final String id;
    private final String username;
    private String password;
    private  Collection<? extends GrantedAuthority> authorities;
    private  Date lastPasswordResetDate = null;

    /**
     * JWT转换UserDetails对象用
     * @param id
     * @param username
     * @param roles
     */
    public LocalUserDetails(
            String id,
            String username,
            List<LinkedHashMap> roles) {
        this.id = id;
        this.username = username;
        this.authorities = rolesToAuthority(roles);
    }

    /**
     * JDBC转换UserDetails用
     * @param id
     * @param username
     * @param password
     * @param authorities
     */
    public LocalUserDetails(
            String id,
            String username,
            String password,
            Collection<? extends GrantedAuthority> authorities) {
        this.id = id;
        this.username = username;
        this.password = password;
        this.authorities = authorities;
    }

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        return authorities;
    }

    private  Collection<? extends GrantedAuthority> rolesToAuthority(List<LinkedHashMap> roles){
        Collection<SimpleGrantedAuthority> authorities = new ArrayList<>(roles.size());
        for (LinkedHashMap<String,String> role : roles) {
            authorities.add(new SimpleGrantedAuthority(role.get("authority")));
        }
        return authorities;
    }

    public String getId() {
        return id;
    }

    @Override
    public String getPassword() {
        return password;
    }

    @Override
    public String getUsername() {
        return username;
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return true;
    }

    public Date getLastPasswordResetDate() {
        return lastPasswordResetDate;
    }
}
